/**
 * 
 */
package com.spikylee.hyves4j.util;

import java.util.HashMap;

//import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 * @author Miroslav Vujicic
 * 
 */
public class NodeUtil {

	final static Logger logger = LoggerFactory.getLogger(NodeUtil.class);

	private HashMap<String, String> context;

	public NodeUtil(Node node) {
		context = getMap(node, "");
	}
	
	
	private HashMap <String, String> getMap (Node node, String prefix) {
		
		if (!node.hasChildNodes()) {
			return null;
		}

		HashMap<String, String> map = new HashMap<String, String>();
		NodeList list = node.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			Node subnode = list.item(i);
			if (subnode.getNodeType() == Node.ELEMENT_NODE) {
				String key = prefix + subnode.getNodeName();
				String value = null;
				if (subnode.getFirstChild() != null) {
					Node child = subnode.getFirstChild();
					if (child.getNodeType() == Node.TEXT_NODE) {
						value =  ((Text) subnode.getFirstChild()).getData();
					} else if (child.getNodeType() == Node.ELEMENT_NODE) {
						map.putAll(getMap(subnode, key + "/"));
					}
				}
				map.put(key, value);
			} else {
				logger.debug(subnode.getNodeType() + " " + subnode.getNodeName());
			}
		}
		return map;
	}
	

	
	public String getStringValue(String element) {
		
		if (element.startsWith("/")) {
			element = element.substring(1);
		}
		logger.debug("context[" + element + "] = " + context.get(element));
		return context.get(element);
		
	}

    public int getIntValue(String element) {
        try {
            return Integer.parseInt((String) getStringValue(element));
        } catch (NumberFormatException e) {
            return 0;
        }
    }
    
    public long getLongValue(String element) {
        try {
            return Long.parseLong((String) getStringValue(element));
        } catch (NumberFormatException e) {
            return 0;
        }
    }
    
    public String toString () {
    	StringBuffer str = new StringBuffer();
    	str.append("[");
    	for(String key: context.keySet()) {
    		str.append("(" + key + ":" + context.get(key) + ")");
    	}
    	return str.append("]").toString();
    }
	
}
